#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2019/6/4 17:26
# @Author  : khz_df
# @Site    : 
# @File    : Client.py
# @Software: ce9nt
import json
import os
import sys
from io import BytesIO

import requests
from selenium import webdriver

from PhpApi import PhpApi


class Config(object):
    base_dir = 'D:' '\\'

    @staticmethod
    def get_log_path_error():
        return Config.base_dir + '4399_error.log'

    @staticmethod
    def get_log_path_csv():
        return Config.base_dir + '4399_check.csv'

    @staticmethod
    def get_captcha_server_url():
        return 'http://192.168.2.88:6000/b'


def my_log(log_info, lv='D'):
    if lv == 'D':
        print(log_info)
    if lv == 'I':
        print(log_info)
    if lv == 'E':
        print(log_info)
        with open(Config.get_log_path_error(), 'a+') as wf:
            wf.write(log_info)
            wf.write('\n')


class Client(object):
    def __init__(self, unit):
        self.uid = unit['id']
        self.gid = unit['gid']
        self.username = unit['account']
        self.password = unit['passwd']
        self.msg = 'undefined'
        self.rapid_info = ''

        self.browser = webdriver.Chrome()
        self.browser.implicitly_wait(3)

        # """http://ptlogin.4399.com/ptlogin/loginFrame.do?postLoginHandler=default&redirectUrl=&displayMode=undefined&css=%2F%2Fs1.img4399.com%2Fwebgame%2Fssjj%2Fnews%2Fcss%2Fptlogin.css%3Fecb1e6f&appId=ssjj&gameId=news&username=&externalLogin=qq&password=&mainDivId=popup_login_div&autoLogin=false&includeFcmInfo=false&qrLogin=true&userNameLabel=4399%E7%94%A8%E6%88%B7%E5%90%8D&userNameTip=%E8%AF%B7%E8%BE%93%E5%85%A54399%E7%94%A8%E6%88%B7%E5%90%8D&welcomeTip=%E6%AC%A2%E8%BF%8E%E5%9B%9E%E5%88%B04399&v=1559703823792"""
        login_url = 'http://ptlogin.4399.com/ptlogin/loginFrame.do?postLoginHandler=default&redirectUrl=&displayMode=undefined&appId=ssjj&gameId=news&username=%s&password=%s&externalLogin=xxx' % (self.username, self.password)
        self.browser.get(login_url)
        my_log(login_url)

    def __del__(self):
        self.browser.quit()

    def _log(self):
        return
        # with open(r'N:\4399_check.json', 'a+') as wf:
        #     msg = '{"id":"%s", "username":"%s", "msg":"%s", "rapid_info":"%s"},' % (self.uid, self.username, self.msg, self.rapid_info)
        #     wf.write(msg)
        with open(Config.get_log_path_csv(), 'a+') as wf:
            msg = '%s\t%s\t%s\t%s\t%s\t%s\n' % (self.uid, self.gid, self.username, self.password, self.msg, self.rapid_info)
            wf.write(msg)

        PhpApi().receiveHaoAccount(self.uid, self.gid, self.username, self.msg, self.rapid_info)

    @staticmethod
    def captcha_req(bytes_png):
        # 识别
        url = Config.get_captcha_server_url()
        files = {'image_file': ('demo.png', BytesIO(bytes_png), 'application')}
        r = requests.post(url=url, files=files)

        # 识别结果
        # print("接口响应: {}".format(r.text))
        predict_text = json.loads(r.text)["value"]
        return predict_text

    def deal_once(self):
        # 00 参数预处理，密码非ascii的时候直接报错
        if self.password.find('\\x') != -1:
            my_log('【Info】密码非ascii', lv='I')
            self.msg = 'df-Invalidate_Password'
            return True

        # 01 检测是否有验证码
        try:
            captcha = self.browser.find_element_by_id('captcha')
            if captcha:
                predict_text = self.captcha_req(captcha.screenshot_as_png)
                self.browser.find_element_by_id('inputCaptcha').send_keys(predict_text)
                my_log('【验证码】uid, predict_text = %s, %s' % (self.uid, predict_text), lv='D')
        except Exception:
            pass

        # 02 点击
        self.browser.find_element_by_id('j-password').send_keys(self.password)
        self.browser.find_element_by_class_name('ptlogin_btn').click()

        # 03 判断结果：成功
        # if self.browser.find_element_by_id('m_all_ser'):
        try:
            if self.browser.find_element_by_class_name('pt_loading'):
                my_log('【Info】验证成功', lv='I')
                self.msg = 'success'
                self.rapid_info = 'default'
                return True
                rapid_info = self.browser.get_cookie('Pauth')
                my_log('{"msg":"%s", "quick_data":"%s"}' % ('success', rapid_info), lv='I')
                my_log('【Info】验证成功', lv='I')
                self.msg = 'success'
                self.rapid_info = rapid_info['value']
                return True
        except Exception:
            # my_log('{"uid":"%s", "msg":"%s", "quick_data":"%s"}' % (self.uid, 'except', ''), lv='E')
            pass

        # 判断结果：失败，密码错误、用户不存在、
        err_msg = self.browser.find_element_by_id('Msg')
        if err_msg.text == '用户不存在' or err_msg.text == '密码错误' or err_msg.text == '密码应为2-20 个字符':
            self.msg = err_msg.text
            my_log('{"uid":"%s", msg":"%s", "quick_data":"%s"}' % (self.uid, err_msg.text, ''), lv='E')
            return True
        if err_msg.text == '' or err_msg.text == '验证码为空' or err_msg.text == '验证码错误' or err_msg.text == '账号异常，请出入验证码':
            my_log('【Info】验证码有误，请重试', lv='I')
            return False
        my_log('{"uid":"%s", msg":"%s", "quick_data":"%s"}' % (self.uid, err_msg.text, ''), lv='E')

        # os.system('PAUSE')
        # self.browser.close()

    def Run(self):
        for i in range(5):
            try:
                if self.deal_once():
                    break
            except Exception as e:
                my_log('【Exception】self.deal_once(unit)。' + str(e), lv='E')
                pass

        self._log()


def main(username, password):
    shelf_id = '0'
    gid = '0'
    account = username
    password = password
    msg = ''
    rapid_info = ''
    unit = """{"id":"%s", "gid":"%s", "account":"%s", "passwd":"%s", "msg":"%s", "rapid_info":"%s"}""" % (
        shelf_id, gid, account, password, msg, rapid_info)
    print(unit)

    unit = json.loads(unit)
    try:
        Client(unit).Run()
    except Exception:
        pass
    # main_easy(username, password)
    return
    """
    browser = webdriver.Chrome()
    browser.implicitly_wait(10)

    browser.get("http://ssjj.4399.com/")
    browser.get("http://my.4399.com/yxssjj/?from=news&amp;newsrefer=")
    "http://ptlogin.4399.com/ptlogin/loginFrame.do?postLoginHandler=default&redirectUrl=&displayMode=undefined&css=%2F%2Fs1.img4399.com%2Fwebgame%2Fssjj%2Fnews%2Fcss%2Fptlogin.css%3Fecb1e6f&appId=ssjj&gameId=news&username=&externalLogin=qq&password=&mainDivId=popup_login_div&autoLogin=false&includeFcmInfo=false&qrLogin=true&userNameLabel=4399%E7%94%A8%E6%88%B7%E5%90%8D&userNameTip=%E8%AF%B7%E8%BE%93%E5%85%A54399%E7%94%A8%E6%88%B7%E5%90%8D&welcomeTip=%E6%AC%A2%E8%BF%8E%E5%9B%9E%E5%88%B04399&v=1559703823792"
    # browser.close()

    # browser.find_element_by_class_name('E_acct').text('cheng1751343638')
    # browser.find_element_by_class_name('E_passwd').text('chengbeiailulu.0')
    browser.switch_to.frame(browser.find_element_by_id('flash22'))
    browser.switch_to.frame(browser.find_element_by_id('popup_login_frame'))
    my_log(browser.find_element_by_xpath('//*[@id="username"]'))
    browser.find_element_by_xpath('//*[@id="username"]').send_keys('cheng1751343638')
    browser.find_element_by_xpath('//*[@id="password"]').send_keys('asdqwe784936577')
    # browser.find_element_by_xpath('//*[@id="m_commonLogin"]/div[5]/a[1]').click()
    # browser.find_element_by_xpath('<input type="submit" value="" class="ptlogin_btn">').click()
    login_btn = browser.find_element_by_class_name('ptlogin_btn')
    my_log(login_btn)

    login_btn.click()

    # 判断结果：成功
    # if browser.find_element_by_id('m_all_ser'):
    if browser.find_element_by_class_name('pt_loading'):
        result = 0

    # 验证码

    # 判断结果：失败，密码错误、用户不存在、
    err_msg = browser.find_element_by_id('Msg')
    my_log(err_msg, lv='i')

    os.system('PAUSE')
    """


if __name__ == "__main__":
    my_log("------------------    Enter __main__    ------------------")

    my_log(u"[Current work directory is : ]\t" + os.getcwd())
    my_log(u"[Current process ID is : ]\t" + str(os.getpid()))
    my_log("\n")
    if len(sys.argv) == 1:      # 无参数
        sys.argv.append('cheng1751343638')
        sys.argv.append('asdqwe784936577')

    username = sys.argv[1]
    password = sys.argv[2]
    main(username, password)
    exit(0)

    # with open(r'N:\_TMP\captcha_prj\__release\accounts.json') as rf:
    with open(r'N:\4399_accounts_0.txt') as rf:
        json_accounts = rf.read()
        json_accounts = json_accounts.replace('\\', '\\\\')
        obj_accounts = json.loads(json_accounts, encoding='utf-8')
        if obj_accounts['status'] != 1:
            print('【Error】 status != -1')
            exit(-1)

        for unit in obj_accounts['data']:
            print(unit)
            try:
                Client(unit).Run()
            except Exception:
                pass

    browser = webdriver.Chrome()
    browser.quit()

    my_log("------------------    Leave __main__    ------------------")
